import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myflutterdemo/model/CommonModel.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String result = '';

  Future<CommonModel> fetchGet() async {
    final url = Uri.http('jsonplaceholder.typicode.com', 'posts/2');
    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        final res = json.decode(response.body);
        return CommonModel.fromJson(res);
      } else {
        throw Exception('Failed to load data');
      }
    } catch (e) {
      throw Exception('Failed to connect to the server');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('http'),
      ),
      body: Column(
        children: <Widget>[
          ElevatedButton(
            child: const Text('搜索'),
            onPressed: () {
              fetchGet().then((CommonModel value) {
                setState(() {
                  result = '请求结果：${value.title}';
                });
              }).catchError((error) {
                setState(() {
                  result = '请求失败：$error';
                });
              });
            },
          ),
          Text(result)
        ],
      ),
    );
  }
}
